package com.sunfeng.chap5.selectkey;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * 将两个不同的通道注册到相同的选择器中   出现重复消费的情况
 */
public class Test104 {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel1 = ServerSocketChannel.open();
        serverSocketChannel1.bind(new InetSocketAddress("localhost", 7777));
        serverSocketChannel1.configureBlocking(false);

        ServerSocketChannel serverSocketChannel2 = ServerSocketChannel.open();
        serverSocketChannel2.bind(new InetSocketAddress("localhost", 8888));
        serverSocketChannel2.configureBlocking(false);

        Selector selector1 = Selector.open();

        SelectionKey selectionKey1 = serverSocketChannel1.register(selector1, SelectionKey.OP_ACCEPT);
        SelectionKey selectionKey2 = serverSocketChannel2.register(selector1, SelectionKey.OP_ACCEPT);

        boolean isRun=true;

        while (isRun==true) {
            int keyCount = selector1.select();
            Set<SelectionKey> selectionKeySet1 = selector1.keys();
            Set<SelectionKey> selectionKeySet2 = selector1.selectedKeys();
            System.out.println("keyCount"+keyCount);
            System.out.println("selectionKeySet1 size()"+selectionKeySet1.size());
            System.out.println("selectionKeySet2 size()"+selectionKeySet2.size());
            Iterator<SelectionKey> iterator = selectionKeySet2.iterator();
            while (iterator.hasNext()) {
                SelectionKey next = iterator.next();
                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) next.channel();
                SocketChannel socketChannel = serverSocketChannel.accept();
                if (socketChannel == null) {
                    System.out.println("打印这条信息表明是练级8888服务器时重复消费的情况");
                    System.out.println("讲7777关联的SelectKey对应的SocketChannel通道取出来");
                    System.out.println("socketchannel为null");
                }
                InetSocketAddress localAddress = (InetSocketAddress) serverSocketChannel.getLocalAddress();
                System.out.println(localAddress.getPort() + "被客户端链接了");
                System.out.println();
            }
        }
        serverSocketChannel1.close();
        serverSocketChannel2.close();


    }
}
